package com.develop.jdbc.jdbc.connection;

import com.alibaba.druid.pool.DruidDataSource;
import com.develop.jdbc.util.StringHelper;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * 描述:	 获取datasource.xml数据库配置信息
 * 版权:	 Copyright (c) 2005
 * 公司:	 -
 * 作者:	 fenny
 * 版本:	 1.0
 * 创建日期: 2006-10-4
 * 创建时间: 21:33:09
 */
public final class Configure {

    private static final Logger log = LoggerFactory.getLogger(Configure.class);
    /**
     * 数据库配置文件
     */
    private static final String CONFIG_FILE_NAME = "datasource.xml";

    private static String DEFAULT = "";
    private static Configure instance = new Configure();
    private static Map<String, DruidDataSource> dataSourceMap = new HashMap<>();

    static {
        loadConfig();
    }

    private Configure() {
    }

    /**
     * 描述：获取实例
     * 作者：fenny
     *
     * @return
     */
    public static Configure getInstance() {
        return instance;
    }

    /**
     * 描述：销毁数据源
     */
    public static void destroyDataSource() {
        try {
            DruidDataSource druidDataSource;
            for (String key : dataSourceMap.keySet()) {
                druidDataSource = dataSourceMap.get(key);
                druidDataSource.close();
            }
        } catch (Exception e) {
            log.error("", e);
        }
    }


    private static void loadConfig() {
        try {
            InputStream is = Configure.class.getResourceAsStream("/" + CONFIG_FILE_NAME);
            SAXReader reader = new SAXReader();
            Document document = reader.read(is);
            if (document == null) {
                return;
            }
            //得到根元素
            Element rootElement = document.getRootElement();
            DEFAULT = rootElement.attributeValue("default", "");
            DruidDataSource dataSource;
            Properties properties;
            List funcElementList = rootElement.elements("datasource");
            for (Object o : funcElementList) {
                Element dsElement = (Element) o;
                String id = dsElement.attributeValue("id", "");
                if (StringHelper.isEmpty(id)) {
                    continue;
                }
                properties = new Properties();
                List propElementList = dsElement.elements("property");
                for (Object o1 : propElementList) {
                    Element propElement = (Element) o1;
                    String name = propElement.attributeValue("name");
                    String value = propElement.getTextTrim();
                    properties.put(name, value);
                }
                dataSource = buildDataSource(properties);
                if (dataSource != null) {
                    dataSourceMap.put(id, dataSource);
                }
            }
        } catch (Exception ex) {
            log.error("", ex);
        }
    }

    /**
     * 创建数据源
     *
     * @param properties
     * @return
     */
    private static DruidDataSource buildDataSource(Properties properties) {
        try {
            DruidDataSource druidDataSource = new DruidDataSource();
            druidDataSource.configFromPropety(properties);
            druidDataSource.init();
            return druidDataSource;
        } catch (Exception ex) {
            log.error("", ex);
        }
        return null;
    }

    /**
     * 获得缺省数据源
     *
     * @return
     */
    public DataSource getDataSource() {
        //若只有一个数据源，则直接返回相应的数据源
        if (dataSourceMap.size() == 1) {
            Object[] dataSourceArray = dataSourceMap.values().toArray();
            return (DataSource) dataSourceArray[0];
        }
        //若有多个数据源，则查找缺省数据源
        if (StringHelper.isEmpty(DEFAULT)) {
            return null;
        }
        return getDataSource(DEFAULT);
    }

    /**
     * 根据datasource.xml文件中配置的数据源ID，得到对应的数据源对象
     *
     * @param id
     * @return
     */
    public DataSource getDataSource(String id) {
        return (DataSource) dataSourceMap.get(id);
    }

    /**
     * 描述：判断datasourceid是否存在
     * 作者：fenny
     * 时间：Dec 8, 2011 11:20:47 AM
     *
     * @param id
     * @return
     */
    public static boolean isExistDataSource(String id) {
        return dataSourceMap.containsKey(id);
    }

}